package jdl.databaseObjects.sqlite.datatypes;

import java.util.List;

import jdl.databaseObjects.DbType;
import jdl.databaseObjects.DbTypeUnknownException;
import jdl.tokenization.Token;
import jdl.tokenization.TokenParser;
import jdl.tokenization.TokenType;

public class VarcharDbType extends DbType {
	private int size;

	public VarcharDbType(int size) {
		this.size = size;
	}

	public static DbType fromString(String typeAsString)
			throws DbTypeUnknownException {
		TokenParser parser = new TokenParser();
		List<Token> tokens = parser.getTokens(typeAsString);
		if (tokens.size() != 4)
			throw new DbTypeUnknownException();
		if (tokens.get(3).getTokenType() != TokenType.RIGHT_BRACKET)
			throw new DbTypeUnknownException();
		int size = Integer.parseInt(tokens.get(2).getContent());
		return new VarcharDbType(size);
	}

	@Override
	public String getTypeAsString() {
		String typeName = "varchar";
		if (size > 0) {
			return String.format("%s(%d)", typeName, size);
		}
		return typeName;
	}

	@Override
	public int getSize() {
		return size;
	}
}
